package com.ai.spring.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;

/**
 * 类辅助工具
 *
 * @author 石头
 * @Date 2019/11/18
 * @Version 1.0
 **/
@Slf4j
public class ReflectUtil{
    public static Class<?> forName(String name) {
        try{
            return name2class(name);
        }catch (ClassNotFoundException e){
            throw new IllegalStateException("Not found class " + name + ", cause: " + e.getMessage(), e);
        }
    }

    public static Class<?> name2class(String name) throws ClassNotFoundException {
        return ClassUtils.forName(name,getClassLoader(ReflectUtil.class));
    }

    public static ClassLoader getClassLoader(Class<?> cls) {
        ClassLoader cl = null;
        try{
            cl = Thread.currentThread().getContextClassLoader();
        }catch (Throwable ex){
            // Cannot access thread context ClassLoader
        }
        if (cl == null) {
            // No thread context class loader
            cl = cls.getClassLoader();
        }
        return cl;
    }

}
